<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-select
          v-model="form.status"
          placeholder="状态"
          filterable
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="form.type"
          placeholder="类型"
          filterable
          clearable
          style="width: 170px"
        >
          <el-option
            v-for="item in dict.type"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="form.platform_id"
          placeholder="平台"
          filterable
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="item in dict.platformList"
            :key="item.platform_id"
            :label="item.platform_name"
            :value="item.platform_id"
          />
        </el-select>
        <VCascader
          v-model="form.original_user_id"
          collapse-tags
          key="original_user_id"
          style="width: 200px"
          placeholder="原用户"
        />
        <VCascader
          v-model="form.user_id"
          collapse-tags
          key="user_id"
          style="width: 200px"
          placeholder="新用户"
        />
        <VCascader
          v-model="form.create_user"
          collapse-tags
          key="create_user"
          style="width: 200px"
          placeholder="创建人"
        />
      </template>
      <template #toolbar_btns>
        <el-button
          type="primary"
          @click="handleAdd(null)"
          v-hasPermi="[personnelAuthList.transfer.add]"
        >
          <SvgIcon icon-class="Plus" class="text-[12px] mr-[6px]" />
          新增
        </el-button>
        <el-button
          @click="handleOperation"
          v-hasPermi="[personnelAuthList.transfer.execute]"
        >
          手动执行
        </el-button>
      </template>
    </VTable>
    <Add
      :data="addData"
      :title="addTitle"
      v-model="addVisible"
      @close="addData = null"
      :option="dict"
      @refresh="handelRefresh"
    />
    <Details
      v-model="detailsVisible"
      :id="detailsId"
      @close="detailsId = null"
    />
    <VLog ref="transferLogRef" class="dialogPublic" :api="transferLog"></VLog>
  </VPage>
</template>
<script lang="jsx" setup>
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import Add from "./add/index.vue";
import Details from "./details/index.vue";
import VLog from "@/components/VLog";
import { isPermission } from "@/hooks/permission.js";
import { personnelAuthList } from "@/Auth/personnel.js";
const { proxy } = getCurrentInstance();
import { transferList, transferRun, transferDel, transferLog } from "./api";
import { getDictList, getPlatform, getShop, getSites } from "@/api/public.js";
import { statusList } from "./data.js";
const tableOptins = reactive({
  formConfig: {
    data: {
      name: "",
    },
  },
  columns: [
    { type: "checkbox", width: "60", fixed: "left" },
    { field: "id", title: "ID", width: "60", fixed: "left" },
    { field: "platform", title: "平台", minWidth: "90", fixed: "left" },
    {
      field: "shop",
      title: "店铺/站点",
      minWidth: "200",
      fixed: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row?.shop_desc || "-"}/{row?.site_desc || "-"}
            </div>
          );
        },
      },
    },
    { field: "original_username", title: "原用户", minWidth: "200" },
    { field: "username", title: "新用户", minWidth: "200" },
    { field: "exec_type_desc", title: "执行类型", minWidth: "200" },
    { field: "exec_time", title: "执行时间", minWidth: "200" },
    {
      field: "period_time",
      title: "时间范围",
      minWidth: "300",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row?.period_start_time} ~ {row?.period_end_time}
            </div>
          );
        },
      },
    },
    {
      field: "update_user_text",
      title: "执行状态/详情",
      minWidth: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.exec_status_desc}
              <el-button
                type="primary"
                link
                onClick={() => handleCheck(row.id)}
              >
                详情
              </el-button>
            </div>
          );
        },
      },
    },
    { field: "remark", title: "备注", minWidth: "200" },
    { field: "create_username", title: "创建人", minWidth: "200" },
    { field: "create_time", title: "创建时间", minWidth: "200" },
    { field: "update_time", title: "更新时间", minWidth: "200" },
    {
      title: "操作",
      width: "140",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {isPermission([personnelAuthList.transfer.edit]) &&
                row?.exec_status == 0 && (
                  <el-button type="primary" link onClick={() => handleAdd(row)}>
                    编辑
                  </el-button>
                )}
              {isPermission([personnelAuthList.transfer.delete]) &&
                (row?.exec_status == 0 || row?.exec_status == 4) && (
                  <el-button
                    type="danger"
                    link
                    onClick={() => handleDelete(row.id)}
                  >
                    删除
                  </el-button>
                )}
              <el-button type="primary" link onClick={() => handleLog(row.id)}>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: true,
    ajax: {
      query: ({ page, form }) => {
        return transferList({ ...form, ...page }).then((res) => {
          res?.data?.forEach((item) => {
            item.shop_desc =
              item?.shop?.map((e) => e.shop_name).join(",") || null;
          });
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const dict = reactive({
  type: [], //执行类型
  platformList: [], //平台
  shopList: [], //店铺
  sitesList: [], //站点
});
//获取字典数据
const getDict = async () => {
  dict.type = [];
  try {
    const res = await getDictList({
      dict_type_id: 1,
    });
    const groupedData = res?.data?.reduce((acc, item) => {
      const key = item.tag;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item);
      return acc;
    }, {});
    dict.type = groupedData;
    console.log(groupedData);
  } catch (error) {
    console.log(error);
  }
};
//获取平台数据
const getPlatformData = async () => {
  try {
    const res = await getPlatform();
    dict.platformList = res.data || [];
  } catch (error) {
    console.log(error);
  }
};
//获取店铺数据
const getShopData = async () => {
  try {
    const res = await getShop();
    dict.shopList = res.data || [];
  } catch (error) {
    console.log(error);
  }
};
//获取站点数据
const getSitesData = async () => {
  try {
    const res = await getSites();
    dict.sitesList = res.data || [];
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  getDict();
  getPlatformData();
  getShopData();
  getSitesData();
});
//新增/编辑
const addData = ref(null);
const addTitle = ref("新增");
const addVisible = ref(false);
const handleAdd = (val) => {
  if (val) {
    addData.value = val;
    addTitle.value = "编辑";
  } else {
    addData.value = null;
    addTitle.value = "新增";
  }
  addVisible.value = true;
};
//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords();
  if (!getCheckboxRecords.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return false;
  }
  const arr = [];
  getCheckboxRecords.map((e) => {
    arr.push(e.id);
  });
  return arr;
};
//手动执行
const handleOperation = () => {
  let id = getSelectRow();
  if (!id) return;
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认手动执行选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await transferRun({ transfer_id: id });
          if (code !== 200) return ElMessage.error(message);
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handelRefresh();
        }
      } else {
        done();
      }
    },
  });
};
//删除
const handleDelete = (id) => {
  if (!id) return;
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await transferDel({ id });
          if (code !== 200) return ElMessage.error(message);
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handelRefresh();
        }
      } else {
        done();
      }
    },
  });
};
//日志
const transferLogRef = ref();
const handleLog = (id) => {
  transferLogRef.value.open(id);
};
//详情
const detailsVisible = ref(false);
const detailsId = ref(null);
const handleCheck = (val) => {
  detailsVisible.value = true;
  detailsId.value = val;
};
const tableRef = ref();
const handelRefresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
<style lang="scss" scoped></style>
